package com.szlanyou.thirdsdk.retrofit.interceptor;

import android.text.TextUtils;

import com.szlanyou.thirdsdk.retrofit.util.MyLogUtil;
import com.szlanyou.thirdsdk.retrofit.util.RequestBodyUtil;
import com.szlanyou.thirdsdk.retrofit.util.TimeCountHelper;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * author:@author 陈章 on 2016/6/21 0021.
 * des:
 * 自定义日志过滤器
 */
public class MyLogInterceptor implements Interceptor {
    private TimeCountHelper timeCountHelper = new TimeCountHelper();

    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String requestInfo;
        String requestHttpUrl = request.url().toString();
        RequestBody requestBody = request.body();

        if(requestBody != null){
            long contentLength  = requestBody.contentLength();
            if(contentLength < 2000){
                String jsonFromRequestBody = RequestBodyUtil.getJsonFromRequestBody(requestBody);
                requestInfo = String.format(Locale.getDefault(), ">>>>>>request:\nmethod=%s\nurl=%s\nheaders=%s\nrequestBodyJson=%s", request.method(),requestHttpUrl,request.headers(), jsonFromRequestBody);
            }else{
                MyLogUtil.d("用户可能在传输文件，jsonFromRequestBody特别大，就不打印了。");
                requestInfo = String.format(Locale.getDefault(), ">>>>>>request:\nmethod=%s\nurl=%s\nheaders=%s\n",request.method(), requestHttpUrl,request.headers());
            }
        }else{
            requestInfo = String.format(Locale.getDefault(), ">>>>>>request:\nmethod=%s\nurl=%s\nheaders=%s\n", request.method(),requestHttpUrl,request.headers());
        }

        MyLogUtil.d(requestInfo);

        OkHttpRequestCacher.getInstance().setRequestInfo(requestInfo);
        timeCountHelper.markStartCount();

        okhttp3.Response response = chain.proceed(chain.request());
        MyLogUtil.d(String.format(Locale.getDefault(), "<<<<<<response for %s in %s ms%n%s",
                response.request().url(), timeCountHelper.getPassedTimeMillis(), response.headers()));


        //下载时，由于responseBody.byteStream()会与response.body()的执行产生冲突，然后产生的现象是
        //这里会阻塞很久才执行，好像是在缓冲要下载的文件，然后下载文件瞬间就执行完了，像是从本地复制文件一样。
        if(!ShareInfoHelper.getDownloadUrlCacheList().contains(requestHttpUrl)){
            //注意千万不可使用response.body().string()打印，否则会报错。
            BufferedSource source = response.body().source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset UTF8 = Charset.forName("UTF-8");
            String body = buffer.clone().readString(UTF8);
            if(body != null && body.length() < 2000){
                MyLogUtil.d(" body返回结果<<\n" + body);
            }else{
                MyLogUtil.d(" body 过大，可能是在下载文件，不打印了。");
            }
        }else{
            MyLogUtil.d(" 下载文件，不打印body。");
        }
        return response;
    }
}
